package com.example.yydm666.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yydm666.entity.Cart;
import com.example.yydm666.entity.Product;
import com.example.yydm666.enums.ResultEnum;
import com.example.yydm666.exception.YydmException;
import com.example.yydm666.mapper.CartMapper;
import com.example.yydm666.mapper.ProductMapper;
import com.example.yydm666.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yydm666.vo.CartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-03-28
 */
@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    //扣库存为0弹出库存不足
    @Override
    public boolean save(Cart entity) {
//        扣除库存
        Product product = productMapper.selectById(entity.getProductId());
        Integer stock = product.getStock() - entity.getQuantity();
        product.setStock(stock);
        if (stock < 0) {
            log.error("[添加购物车]库存不足", stock);
            throw new YydmException(ResultEnum.STOCK_ERROR);
        }
        productMapper.updateById(product);
        if (cartMapper.insert(entity) == 1) {
            return true;
        }
        return false;
    }

    //购物车商品列表
    @Override
    public List<CartVO> findAllCartVOByUserId(Integer id) {
        List<CartVO> cartVOList = new ArrayList<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", id);
        List<Cart> cartList = cartMapper.selectList(wrapper);
        for (Cart cart : cartList) {
            CartVO cartVO = new CartVO();
            Product product = productMapper.selectById(cart.getProductId());
            BeanUtils.copyProperties(product, cartVO);
            BeanUtils.copyProperties(cart, cartVO);
            cartVO.setProductId(product.getId());
            cartVOList.add(cartVO);
        }
        return cartVOList;
    }

}
